package com.example.my.nanyibangz.ui.danpin;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.my.nanyibangz.R;
import com.example.my.nanyibangz.base.BaseFragment;
import com.example.my.nanyibangz.bean.DanPin_Beans;
import com.example.my.nanyibangz.bean.DataBean;
import com.example.my.nanyibangz.config.DanPinUrlConfig;
import com.example.my.nanyibangz.ui.danpintype.DpTypeActivity;
import com.example.my.nanyibangz.ui.danpintypeclick.DanPinTypeClickLowerActivity;
import com.example.my.nanyibangz.utils.CustomGridLayoutManager;
import com.example.my.nanyibangz.utils.CustomGridView;
import com.example.my.nanyibangz.utils.CustomerNestScrollView;
import com.example.my.nanyibangz.utils.DividerGridItemDecoration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by My on 2016/10/7.
 */

public class DPFragmentVp extends BaseFragment implements DPFragmentVPContact.View {
    @Bind(R.id.dp_type_cgv)
    CustomGridView dpTypeCgv;//用来装填单品type的自定义gridview*/
    @Bind(R.id.dp_jingxuan_txt)
    TextView dpJingxuanTxt;//用来显示单品-精选标题（例如上衣精选）
    /* @Bind(R.id.dp_jingxuan_cgv)
     CustomGridView dpJingxuanCgv;//用来装填单品精选的自定义gridview*/
    @Bind(R.id.danpin_swiperefreshlayout)
    SwipeRefreshLayout danpinSwiperefreshlayout;//用swipRefreshLayout实现上拉刷新，下拉加载。
    @Bind(R.id.recycle_view_jingxuan)
    RecyclerView recycleViewJingxuan;//用来装填单品精选的自定义gridview;
    @Bind(R.id.danpin_nestedScrollView)
    CustomerNestScrollView danpinNestedScrollView;
    int page = 1;//页数
    @Bind(R.id.ll_footer)
    LinearLayout llFooter;
    @Bind(R.id.txt_pull_to_up)
    TextView txtPullToUp;
    private DPFragmentVPContact.Presenter presenter;//单品type的中间者
    private DPFragmentVPContact.Presenter presenter_jingxuan;//单品精选的中间者
    private String cateId = "";//用来接收danpin_beans的cardId ，
    DanPinTypeAdapter adapter;//用来给单品type的gridview填充数据。
    DanPinTypeClickRecycleViewAdapter2 danPin_jingXuan_adapter;
    private List<DataBean> list_jingxuan;//单品精选的集合。
    private List<DanPin_Beans.DataBean.CategoriesBean> list_categroiBeans;//单品种类的集合，以便通过get得到要传递的每一个种类的cate_id.
    private int lastVisibleItem;//recycler最后一项；
    CustomGridLayoutManager gridLayoutManager;
    private View view_danpin;//为了得到单品主页的布局文件
    private FloatingActionButton fab;//悬浮按钮

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dp_vp, null);
        ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initFab();  //得到并初始化fab
        initview();
        InitViewRecycleView();
        SwipRefeshLayout();//下拉刷新
        dapin_type_cgv_Click();//点击单品type实现跳转。
        scrollBottom();//滑动到底部
        scrollUp();//监听nestedScrollview的上下滑动，
    }
    //得到并初始化fab
    public void initFab(){
        //view_danpin=LayoutInflater.from(getActivity()).inflate(R.layout.fragment_dp,null);
        fab= (FloatingActionButton) getActivity().findViewById(R.id.dp_type_fab);
    }

    //调用presenter的方法
    public void initview() {
        presenter = new DPFragmentVPPresenter(this);
        // http://api.nanyibang.com/select-condition?administrativeArea=%E5%8C%97%E4%BA%AC%E5%B8%82&age=24&channel=yingyongbao&country=%E4%B8%AD%E5%9B%BD&locality=%E5%8C%97%E4%BA%AC%E5%B8%82&system_name=android&versionCode=219
        Map<String, String> params = new HashMap<>();
        params.put(DanPinUrlConfig.Params.AdministrativeArea, DanPinUrlConfig.DefaultVaule.AdministrativeArea_VALUE);
        params.put(DanPinUrlConfig.Params.Age, DanPinUrlConfig.DefaultVaule.Age_VALUE);
        params.put(DanPinUrlConfig.Params.Channel, DanPinUrlConfig.DefaultVaule.Channel_VALUE);
        params.put(DanPinUrlConfig.Params.Country, DanPinUrlConfig.DefaultVaule.Country_VALUE);
        params.put(DanPinUrlConfig.Params.Locality, DanPinUrlConfig.DefaultVaule.Locality_VALUE);
        params.put(DanPinUrlConfig.Params.System_name, DanPinUrlConfig.DefaultVaule.System_name_VALUE);
        params.put(DanPinUrlConfig.Params.VersionCode, DanPinUrlConfig.DefaultVaule.VersionCode_VALUE);
        presenter.getVerticalFromNet_DanPin_Beans(params);


    }

    //精选的gridview需要的地址。
    public void InitView_JingXuan(int page) {

        presenter_jingxuan = new DPFragmentVPPresenter(this);
        Map<String, String> params_jingxuan = new HashMap<>();
        //http://api.nanyibang.com/tuijian-product?age=19&cateId=2&channel=xiaomi&page=1&system_name=android&versionCode=219

        params_jingxuan.put(DanPinUrlConfig.Params.Age, "19");
        params_jingxuan.put(DanPinUrlConfig.Params.CateId, cateId);
        params_jingxuan.put(DanPinUrlConfig.Params.Channel, DanPinUrlConfig.DefaultVaule.Channel_VALUE);
        params_jingxuan.put(DanPinUrlConfig.Params.Page, page + "");
        params_jingxuan.put(DanPinUrlConfig.Params.System_name, DanPinUrlConfig.DefaultVaule.System_name_VALUE);
        params_jingxuan.put(DanPinUrlConfig.Params.VersionCode, DanPinUrlConfig.DefaultVaule.VersionCode_VALUE);
        presenter_jingxuan.getVerticalFromNet_DanPin_JingXuan_Beans(params_jingxuan);
    }

    //初始化recyclerview ,（给recyclervview 指定layoutManager等。）
    public void InitViewRecycleView() {
       /* gridLayoutManager= new CustomGridLayoutManager(getActivity(), 2);
        recycleViewJingxuan.setLayoutManager(gridLayoutManager);*/
        recycleViewJingxuan.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        recycleViewJingxuan.setNestedScrollingEnabled(false);//解滑动决滑动卡顿
        recycleViewJingxuan.addItemDecoration(new DividerGridItemDecoration(getActivity(), 30, 30));
        recycleViewJingxuan.setItemAnimator(new DefaultItemAnimator());//给recycler设置默认动画
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onVerticalSucess_DanPin_Beans(List<DanPin_Beans.DataBean> danPin_Bean_categoriesBean_List) {

        Bundle bundle = getArguments();
        int index = bundle.getInt("index");//传递的单品的viewapger中fragment的索引
        switch (index) {
            case 0:
                dpJingxuanTxt.setText(danPin_Bean_categoriesBean_List.get(index).getName() + "精选");
                cateId = danPin_Bean_categoriesBean_List.get(index).getClassID() + "";
                list_categroiBeans = danPin_Bean_categoriesBean_List.get(index).getCategories();
                adapter = new DanPinTypeAdapter(danPin_Bean_categoriesBean_List.get(index).getCategories(), getActivity());
                dpTypeCgv.setAdapter(adapter);
                InitView_JingXuan(1);
                break;
            case 1:
                cateId = danPin_Bean_categoriesBean_List.get(index).getClassID() + "";
                list_categroiBeans = danPin_Bean_categoriesBean_List.get(index).getCategories();
                dpJingxuanTxt.setText(danPin_Bean_categoriesBean_List.get(index).getName() + "精选");
                adapter = new DanPinTypeAdapter(danPin_Bean_categoriesBean_List.get(index).getCategories(), getActivity());
                dpTypeCgv.setAdapter(adapter);
                InitView_JingXuan(1);
                break;
            case 2:
                cateId = danPin_Bean_categoriesBean_List.get(index).getClassID() + "";
                list_categroiBeans = danPin_Bean_categoriesBean_List.get(index).getCategories();
                dpJingxuanTxt.setText(danPin_Bean_categoriesBean_List.get(index).getName() + "精选");
                adapter = new DanPinTypeAdapter(danPin_Bean_categoriesBean_List.get(index).getCategories(), getActivity());
                dpTypeCgv.setAdapter(adapter);
                InitView_JingXuan(1);
                break;
            case 3:
                cateId = danPin_Bean_categoriesBean_List.get(index).getClassID() + "";
                list_categroiBeans = danPin_Bean_categoriesBean_List.get(index).getCategories();
                dpJingxuanTxt.setText(danPin_Bean_categoriesBean_List.get(index).getName() + "精选");
                adapter = new DanPinTypeAdapter(danPin_Bean_categoriesBean_List.get(index).getCategories(), getActivity());
                dpTypeCgv.setAdapter(adapter);
                InitView_JingXuan(1);
                break;
            case 4:
                cateId = danPin_Bean_categoriesBean_List.get(index).getClassID() + "";
                list_categroiBeans = danPin_Bean_categoriesBean_List.get(index).getCategories();
                //  InitView_JingXuan(1);//调用方法给精选gridview地址参数赋值。
                dpJingxuanTxt.setText(danPin_Bean_categoriesBean_List.get(index).getName() + "精选");
                adapter = new DanPinTypeAdapter(danPin_Bean_categoriesBean_List.get(index).getCategories(), getActivity());
                dpTypeCgv.setAdapter(adapter);
                InitView_JingXuan(1);

                break;
        }


    }

    @Override
    public void onVerticalFail_DanPin_Beans(String msg) {
    }

    @Override
    public void onVerticalSucess_DanPin_JingXuan_Beans(final List<DataBean> danPin_JingXuan_List) {

        if (danPin_JingXuan_List.size() != 0) {
            llFooter.setVisibility(View.GONE);
            if (page==1){
                list_jingxuan = danPin_JingXuan_List;
                danPin_jingXuan_adapter = new DanPinTypeClickRecycleViewAdapter2(getActivity(), list_jingxuan);
                Log.i("list", "list===>" + list_jingxuan.size());
                // recycleViewJingxuan.setAdapter(danPin_jingXuan_adapter);
                // danPin_jingXuan_adapter.addItem(list_jingxuan);
                recycleViewJingxuan.setAdapter(danPin_jingXuan_adapter);
                //单品精选recycler的每一项的点击事件
             danPin_jingXuan_adapter.setItemClickListener(new DanPinTypeClickRecycleViewAdapter2.MyItemClickListener() {
                 @Override
                 public void OnItemClick(View view, String Item_id) {
                     Intent intent1 = new Intent(getActivity(), DanPinTypeClickLowerActivity.class);
                     // String item_id = list_jingxuan.get(position).getId() + "";
                     intent1.putExtra("itemId", Item_id);
                     startActivity(intent1);
                     getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                 }
             });
            }else {
                list_jingxuan.addAll(danPin_JingXuan_List);
                danPin_jingXuan_adapter.notifyDataSetChanged();
                //单品精选recycler的每一项的点击事件
                danPin_jingXuan_adapter.setItemClickListener(new DanPinTypeClickRecycleViewAdapter2.MyItemClickListener() {
                    @Override
                    public void OnItemClick(View view, String Item_id) {
                        Intent intent1 = new Intent(getActivity(), DanPinTypeClickLowerActivity.class);
                        intent1.putExtra("itemId", Item_id);//像购买商品页面传递，item_id,pic_url,title,price;
                        //intent1.putExtra("title",);
                        startActivity(intent1);
                        getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
                    }
                });
            }


        } else {
            txtPullToUp.setText("没有更多数据");
        }

    }

    @Override
    public void onVerticalFail_DanPin_JingXuan_Beans(String msg) {

    }

    //swipRefreshLayout实现下拉刷新，
    public void SwipRefeshLayout() {
        //设置研祥进度条的颜色，最多四种。；
        danpinSwiperefreshlayout.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.colorSwipRef));
        danpinSwiperefreshlayout.setColorSchemeResources(R.color.color_holo_yellow, R.color.color_holo_green, R.color.color_holo_he, R.color.color_holo_he2);

        danpinSwiperefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));//调整进度条距离屏幕顶部的距离
        danpinSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //recycleViewJingxuan.setItemAnimator(new DefaultItemAnimator());//给recycler设置默认动画
                        danPin_jingXuan_adapter = new DanPinTypeClickRecycleViewAdapter2(getActivity(), list_jingxuan);
                        //danPin_jingXuan_adapter.notifyDataSetChanged();
                        recycleViewJingxuan.setAdapter(danPin_jingXuan_adapter);
                        danpinSwiperefreshlayout.setRefreshing(false);
                     /*  // CustomGridLayoutManager gridLayoutManager = new CustomGridLayoutManager(getActivity(), 2);
                        recycleViewJingxuan.setLayoutManager(new GridLayoutManager(getActivity(),2));
                        // recycleViewJingxuan.setLayoutManager(gridLayoutManager);
                        recycleViewJingxuan.setNestedScrollingEnabled(false);//解滑动决滑动卡顿
                        recycleViewJingxuan.addItemDecoration(new DividerGridItemDecoration(getActivity(), 30,30));


                      ;*/
                        // InitView_JingXuan(1);
                    }
                }, 3000);
            }
        });
    }

    //单品type的gridview点击事件，（例如点击上衣里的，长袖T恤）跳转页面
    public void dapin_type_cgv_Click() {
        dpTypeCgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String cate_id = list_categroiBeans.get(position).getCateId() + "";//从categroiy中得到的cate_id.传递到点击跳转的页面中，用于拼接地址。
                Intent intent = new Intent(getActivity(), DpTypeActivity.class);
                intent.putExtra("cateId", cate_id);
                intent.putExtra("typename", list_categroiBeans.get(position).getName());
                startActivity(intent);
                //设置页面跳转的动画效果，左近右出
                getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);

            }
        });
    }


    //scrollView滑动到底部
    public void scrollBottom() {
        danpinNestedScrollView.setOnScrollToBottomLintener(new CustomerNestScrollView.OnScrollToBottomListener() {
            @Override
            public void onScrollBottomListener(boolean isBottom) {
                if (isBottom == true) {
                    llFooter.setVisibility(View.VISIBLE);//如果到底部，llfooter就可见
                    InitView_JingXuan((++page));
                }

            }
        });
    }

    //滑动到判断上滑还是下滑。
    public void scrollUp(){
        danpinNestedScrollView.setScrollListener(new CustomerNestScrollView.ScrollListener() {
            @Override
            public void scrollOritention(String oritentsion) {
                if("down".equals(oritentsion)){
                    Log.i("zz","向下滑动");
                   // fab.setVisibility(View.GONE);
                   fab.show();


                }else if ("up".equals(oritentsion)) {
                    //fab.setVisibility(View.VISIBLE);
                    Log.i("zz","向上滑动");
                    fab.hide();
                    /**
                     * anim文件夹下存放的是补间动画，
                     * animator下面存放的是属性动画。
                     */

                    // 加载动画(上滑时fab由小逐渐变大)
                  /*  Animator anim = AnimatorInflater.loadAnimator(getActivity(),R.animator.fab_smalltobig);
                    anim.setTarget(fab);
                    anim.start();*/
                }else {
                    Log.i("sb","nmb");
                }
            }
        });
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return super.onCreateAnimation(transit, enter, nextAnim);
    }
}